package com.google.code.pj2r.sample.simple.resources;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.code.pj2r.DataAccessException;
import com.google.code.pj2r.MarshallingException;
import com.google.code.pj2r.Resource;
import com.google.code.pj2r.ResourceConflictException;


public abstract class DojoItemFileStoreResource implements Resource {

	public abstract String create() throws DataAccessException;

	public abstract void delete(String id) throws DataAccessException;

	public abstract String get(String id) throws DataAccessException, MarshallingException;

	public abstract String list() throws DataAccessException, MarshallingException;

	public abstract void update(String id) throws DataAccessException, ResourceConflictException;

	/**
	 * Some Dojo objects require that the json consumed
	 * by the objects is formatted in a certain way. For example
	 * the json consumed by dojo.data.ItemFileWriteStore needs to
	 * have the following struture:
	 *
	 * {
	 * 	label: someLabel,
	 *  identifier: someIdentifier,
	 *  items: [ {item: 'item one'}
	 *  		 {item: 'item two'}
	 *  		]
	 *  }
	 *
	 * This method formats the JSON in a way that the ItemFileWriteStore
	 * and other Dojo objects can consume the json.
	 *
	 * The label and identifier can be omitted.
	 *
	 * @param label
	 * @param identifier
	 * @param items
	 * @return A JSONObject
	 * @throws JSONException
	 */
	public JSONObject addDojoRequiredJSON(String label, String identifier, JSONArray items) throws JSONException{
		if (items == null) {
			throw new IllegalArgumentException("items can't be null");
		}
		JSONObject dojoJSON = new JSONObject();
		if (label != null) {
			dojoJSON.put("label", label);
		}
		if (identifier != null) {
			dojoJSON.put("identifier", identifier);
		}
		dojoJSON.put("items", items);
		return dojoJSON;
	}
}
